<?php
declare(strict_types=1);

namespace App\AdminApi\Modular\System\Controller;

use App\AdminApi\BasicsController;
use App\Common\Extend\Guard\Auth;
use App\Common\Modular\System\Serve\{SeoServe};
use Core\HyperfUnit\Response;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\{Controller, GetMapping, PostMapping};
use Psr\Http\Message\ResponseInterface;
use Zms\HyperfValidateAnnotations\Validate;

#[
    Auth(guard: self::GUARD, label: ['系统管理', 'SEO'], app: self::APP),
    Controller(prefix: "/admin-api/system-seo", server: self::SERVER)
]
class SeoController extends BasicsController
{
    #[Inject]
    protected SeoServe $server;

    #[
        GetMapping('default-rules'),
        Auth(label: ['查看默认SEO规则'], sign: 'system.seo.get-def', view: '/system/seo/def')
    ]
    public function defaultRules(): ResponseInterface
    {
        return Response::Api()->success(data: $this->server->getDefaultRule());
    }


    #[
        PostMapping('set-default'),
        Auth(label: ['修改默认SEO规则'], sign: 'system.seo.set-def'),
        Validate(
            rules: [
                [['title', 'keywords', 'description'], 'required'],
                ['title', 'string', 'max' => 40],
                ['keywords', 'string', 'max' => 80],
                ['description', 'string', 'max' => 150],
            ],
            labels: ['title' => '默认标题', 'sort' => '默认关键词', 'status' => '默认描述']
        )
    ]
    public function setDefault(): ResponseInterface
    {
        $data = $this->request->getParsedBody();
        if ($this->server->setDefaultRule($data['title'], $data['keywords'], $data['description'])) {
            return Response::Api()->success('设置成功');
        }
        return Response::Api()->fail('设置失败');
    }


    #[
        GetMapping('list'),
        Auth(sign: 'system.seo.list', view: '/system/seo/index')
    ]
    public function list(): ResponseInterface
    {
        $list = $this->server->search()->orderByRaw('id ASC')->paginate($this->pageSize());
        return Response::Api()->success(data: $list);
    }


    #[
        PostMapping('updated'),
        Auth(sign: 'system.seo.updated'),
        Validate(
            rules: [
                ['id', 'required', 'error' => '数据异常,请刷新重试'],
                ['title', 'string', 'max' => 40],
                ['keywords', 'string', 'max' => 80],
                ['description', 'string', 'max' => 150],
            ],
            labels: ['title' => '默认标题', 'sort' => '默认关键词', 'status' => '默认描述']
        )
    ]
    public function updated(): ResponseInterface
    {
        $where = $this->request->inputs(['id', 'title', 'keywords', 'description']);
        if ($this->server->updated($where)) {
            return Response::Api()->success('设置成功');
        }
        return Response::Api()->fail('设置失败');
    }
}